package org.misty.seckill.util;

import com.alibaba.fastjson.JSON;
import org.springframework.util.StringUtils;

public class JSONUtil {
  private JSONUtil() {
  }

  @SuppressWarnings("unchecked")
  public static <T> T parse(String value, Class<T> cls) {
    if (cls == String.class) {
      return (T) value;
    }
    if (StringUtils.isEmpty(value)) {
      return null;
    }
    return JSON.parseObject(value, cls);
  }

  public static <T> String toJsonString(T value) {
    if (value instanceof String) {
      return value.toString();
    }
    return JSON.toJSONString(value);
  }

  public static void main(String[] args) {
    System.out.println(toJsonString(1));
    System.out.println(toJsonString(1L));
    System.out.println(toJsonString(1.2));
    System.out.println(toJsonString("string"));
    System.out.println(toJsonString(true));

    var i = parse("1", int.class);
    System.out.println(i);

    var l = parse("1", long.class);
    System.out.println(l);

    var d = parse("1.2", double.class);
    System.out.println(d);

    var str = parse("\"string\"", String.class);
    System.out.println(str);

    var b = parse("true", boolean.class);
    System.out.println(b);
  }
}
